#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;

const ll N = 2e4 + 10, INF = 0x3f3f3f3f3f3f3f3f;


ll n, m;
ll s[N], t[N];
ll f[410][410];

inline ll read()
{
    ll x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch>'9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9')
        x = x * 10 + ch - '0', ch = getchar();
    return x * f;
}

void solve()
{
    cin >> n >> m;
    for (ll i = 1;i <= n;i++) {
        s[i] = read();
        s[i + n] = s[i];
    }
    for (ll i = 1;i <= n;i++) {
        t[i] = read();
        t[i + n] = t[i];
    }

    memset(f, 0x3f, sizeof f);

    for (ll i = 1; i <= 400; i++) f[i][i] = 0;

    for (ll i = 1;i <= m;i++) {
        ll a, b, c;a = read();b = read();c = read();
        f[a][b] = min(f[a][b], c);
    }

    for (ll k = 1; k <= 400; k++)
        for (ll i = 1; i <= 400; i++)
            for (ll j = 1; j <= 400; j++)
                f[i][j] = min(f[i][j], f[i][k] + f[k][j]);

    ll ans = INF;
    for (ll st = 1;st <= n;st++) {
        ll sum = 0;
        for (ll i = 1, j = st;i <= n;i++, j++) {
            if (f[s[i]][t[j]] == INF && f[t[j]][s[i]] == INF) { sum = INF;break; }
            sum += min(f[s[i]][t[j]], f[t[j]][s[i]]);
        }
        ans = min(ans, sum);
    }
    if (ans == INF) {
        cout << -1 << '\n';
    } else cout << ans << '\n';
}

signed main()
{
    //ios::sync_with_stdio(0); 
    //cin.tie(0);cout.tie(0);
#define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    ll T = 1;
    //cin>>T;
    for (ll i = 1;i <= T;i++) {
        solve();
    }
}